﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;

namespace Extensions
{
    public static class IServiceCollectionExtensions
    {
        /// <summary>
        /// 根据类型批量注入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddGlobalServices<T>(this IServiceCollection services) where T : class
        {
            var baseType = typeof(T);

            var assembly = baseType.Module.Assembly;
            var typesList = assembly.GetTypes().ToList().Where(x => x.IsClass && !x.IsAbstract && !x.IsGenericType && !x.IsInterface && x != baseType && baseType.IsAssignableFrom(x)).ToList();
            foreach (var item in typesList)
            {
                services.AddSingleton(item);
            }

            return services;
        }

        ///// <summary>
        ///// 注册配置文件为类
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="services"></param>
        ///// <param name="configuration"></param>
        ///// <returns></returns>
        //public static IServiceCollection AddGlobalServices<T>(this IServiceCollection services, IConfiguration configuration) where T : class, new()
        //{
        //    return services.AddGlobalServices<T>(configuration, new T().GetType().Name);
        //}

        ///// <summary>
        ///// 注册配置文件为类
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="services"></param>
        ///// <param name="configuration"></param>
        ///// <param name="sectionName"></param>
        ///// <returns></returns>
        //public static IServiceCollection AddGlobalServices<T>(this IServiceCollection services, IConfiguration configuration, string sectionName) where T : class, new()
        //{
        //    var model = new T();
        //    services.Configure<T>(configuration.GetSection(sectionName));
        //    configuration.Bind(model.GetType().Name, model);
        //    return services;
        //}
    }
}
